package cn.wei.sdd.core.service.impl;


import cn.wei.common.exception.Assert;
import cn.wei.common.result.ResponseEnum;
import cn.wei.common.utils.MD5;
import cn.wei.sdd.base.util.JwtUtils;
import cn.wei.sdd.core.pojo.entity.Admin;
import cn.wei.sdd.core.mapper.AdminMapper;
import cn.wei.sdd.core.pojo.vo.LoginVO;
import cn.wei.sdd.core.pojo.vo.AdminVO;
import cn.wei.sdd.core.service.AdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author Wei
 * @since 2021-09-22
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {


    @Override
    public String login(LoginVO loginVO) {
        String userName = loginVO.getUserName();
        String password = loginVO.getPassword();

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userName);
        Admin admin = baseMapper.selectOne(queryWrapper);

        //用户是否存在
        Assert.notNull(admin, ResponseEnum.LOGIN_USER_ERROR);

        //校验密码
        Assert.equals(MD5.encrypt(password),admin.getPassword(),ResponseEnum.LOGIN_PASSWORD_ERROR);
        System.out.println(admin);

        //校验是否禁用
        Assert.equals(admin.getStatus(),Admin.STATUS_NORMAL,ResponseEnum.LOGIN_LOKED_ERROR);

        //生成token
        String token = JwtUtils.createToken(admin.getId(), admin.getUserName(),admin.getRole());
        return  token;
    }

    @Override
    public AdminVO getInfo(Long userId) {
        Admin admin = baseMapper.selectById(userId);
        AdminVO adminVO = new AdminVO();
        adminVO.setUserName(admin.getUserName());
        adminVO.setHeadImg(admin.getHeadImg());
        adminVO.setRole(admin.getRole());
        return adminVO;
    }
}
